package com.example.newapp.web.controller;

import com.example.newapp.bean.Account;
import com.example.newapp.service.IAccountService;
import com.example.newapp.utils.Message;
import com.example.newapp.utils.MessageUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@RequestMapping("/account")
@Validated
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @GetMapping("findAll")
    public Message findAll(){
        List<Account> list = accountService.findAll();
        return MessageUtil.success(list);
    }

    @GetMapping("findById")
    public Message findById(long id){
        Account account = accountService.findById(id);
        return MessageUtil.success(account);
    }

    @PostMapping("save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账户名", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query"),
    })
    public Message save(@NotNull String account,@NotNull String password){
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Account a = new Account();
        a.setLoginIp(req.getRemoteAddr());
        a.setAccount(account);
        a.setPassword(password);
        accountService.save(a);
        return MessageUtil.success("保存成功");
    }

    @DeleteMapping("deleteById")
    public Message deleteById(long id){
        accountService.deleteById(id);
        return MessageUtil.success("删除成功");
    }

    @PostMapping("updateById")
    public Message updateById(Account account){
        accountService.updateById(account);
        return MessageUtil.success("更新成功");
    }
}
